package cn.le.util;

import cn.le.bean.ConnectBean;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ConnectionUtil {
    //用户id关系
    private static final Map<Integer, ConnectBean> CONNECT_BEAN_MAP = new ConcurrentHashMap<>();
    //链接id关系
    private static final Map<String, ConnectBean> CHANNEL_BEAN_MAP = new ConcurrentHashMap<>();

    /**
     * 保存连接
     * @param uid
     * @param ctx
     * @param channel
     */
    public static void active(Integer uid, ChannelHandlerContext ctx,ChannelId channel){
        String channelId = String.valueOf(channel);
        ConnectBean bean = new ConnectBean(uid,ctx,channelId);
        CONNECT_BEAN_MAP.put(uid,bean);
        CHANNEL_BEAN_MAP.put(channelId,bean);
    }

    public static void exit(Integer uid){
        ConnectBean bean = CONNECT_BEAN_MAP.get(uid);
        bean.getCtx().close();
        CONNECT_BEAN_MAP.remove(uid);
        CHANNEL_BEAN_MAP.remove(bean.getChannelId());
    }
    public static void exit(ChannelId channel){
        ConnectBean bean = CHANNEL_BEAN_MAP.get(String.valueOf(channel));
        bean.getCtx().close();
        CONNECT_BEAN_MAP.remove(bean.getuId());
        CHANNEL_BEAN_MAP.remove(bean.getChannelId());
    }

    public static ChannelHandlerContext getByImUserId(Integer id){
        ConnectBean connectBean = CONNECT_BEAN_MAP.get(id);
        if (connectBean == null){
            return null;
        }
       return connectBean.getCtx();
    }
}
